﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ParallelRuntimeLibrary.Collections
{
    public class LightLockFreeKeyValueList<T>
    {
        internal int mCount;
        internal KeyValuePair<int, T>[] mArray;
        private const int mDefaultCapacity = 16;
        private int mResizeFlag = 0;

        /*////////////////////////////////////////////////////////////////////////////////////////////////*/

        public LightLockFreeKeyValueList()
            : this(mDefaultCapacity)
        {

        }

        public LightLockFreeKeyValueList(int capacity)
        {
            mArray = new KeyValuePair<int, T>[capacity];
        }

        /*////////////////////////////////////////////////////////////////////////////////////////////////*/

        public void Add(int key, T value)
        {
            if (mCount == mArray.Length) Resize();

            int newItemIndex = Interlocked.Increment(ref mCount);

            mArray[newItemIndex] = new KeyValuePair<int, T>(key, value);
        }

        public bool TryGetValue(int key, out T value)
        {
            for (int i = 0; i < mCount; i++)
                if (mArray[i].Key == key)
                {
                    value = mArray[i].Value;
                    return true;
                }

            value = default(T);
            return false;
        }

        public T this[int key]
        {
            get
            {
                for (int i = 0; i < mCount; i++)
                    if (mArray[i].Key == key)
                        return mArray[i].Value;

                throw new KeyNotFoundException();
            }
            set
            {
                for (int i = 0; i < mCount; i++)
                    if (mArray[i].Key == key)
                    {
                        mArray[i].Value = value;
                        return;
                    }

                throw new KeyNotFoundException();
            }
        }

        public int Count
        {
            get { return mCount; }
        }

        private void Resize()
        {
            if (Interlocked.CompareExchange(ref mResizeFlag, 1, 0) == 0)
            {
                KeyValuePair<int, T>[] NewArray = new KeyValuePair<int, T>[mArray.Length * 2];
                Array.Copy(mArray, NewArray, mArray.Length);
                mArray = NewArray;
                mResizeFlag = 0;
            }
            else
            {
                while (mResizeFlag != 0)
                {
                }
            }
        }


    }
}
